package net.goutalk.glcs.module.system.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import net.goutalk.glcs.common.constant.GlobalConstant;
import net.goutalk.glcs.common.model.result.R;
import net.goutalk.glcs.common.page.ConventPage;
import net.goutalk.glcs.common.page.PageOutput;
import net.goutalk.glcs.common.utils.VoToColumnUtil;
import net.goutalk.glcs.module.system.dto.AddDictionaryDetailDto;
import net.goutalk.glcs.module.system.dto.DictionaryDetailListDto;
import net.goutalk.glcs.module.system.dto.DictionaryDetailPageDto;
import net.goutalk.glcs.module.system.dto.UpdateDictionaryDetailDto;
import net.goutalk.glcs.module.system.entity.DictionaryDetail;
import net.goutalk.glcs.module.system.service.IDictionarydetailService;
import net.goutalk.glcs.module.system.vo.DictionaryDetailListVo;
import net.goutalk.glcs.module.system.vo.DictionaryDetailPageVo;
import net.goutalk.glcs.module.system.vo.DictionaryDetailVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * <p>
 * 数据字典详情 前端控制器
 * </p>
 *
 * @author tanyujie
 * @since 2022-03-17
 */
@RestController
@RequestMapping(GlobalConstant.SYSTEM_MODULE_PREFIX + "/dictionary-detail")
@Api(value = GlobalConstant.SYSTEM_MODULE_PREFIX + "/dictionary-detail",tags = "数据字典详情")
@AllArgsConstructor
public class DictionarydetailController {

    private IDictionarydetailService dictionarydetailService;

    @GetMapping
    @ApiOperation(value = "获取当前数据字典详情（不分页）")
    public R list(DictionaryDetailListDto dto){
        LambdaQueryWrapper<DictionaryDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotEmpty(dto.getName()),DictionaryDetail::getName,dto.getName());
        queryWrapper.eq(StrUtil.isNotEmpty(dto.getCode()),DictionaryDetail::getCode,dto.getCode());
        queryWrapper.eq(ObjectUtil.isNotEmpty(dto.getItemId()) && dto.getItemId() != 0,DictionaryDetail::getItemId,dto.getItemId());
        queryWrapper.select(DictionaryDetail.class, x -> VoToColumnUtil.fieldsToColumns(DictionaryDetailListVo.class).contains(x.getProperty()));
        queryWrapper.orderByAsc(DictionaryDetail::getSortCode);
        List<DictionaryDetail> list = dictionarydetailService.list(queryWrapper);
        return R.ok(BeanUtil.copyToList(list, DictionaryDetailListVo.class));
    }

    @GetMapping("/page")
    @ApiOperation(value = "获取当前数据字典详情（分页）")
    public R page(DictionaryDetailPageDto dto){
        LambdaQueryWrapper<DictionaryDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotEmpty(dto.getName()),DictionaryDetail::getName,dto.getName())
                    .eq(StrUtil.isNotEmpty(dto.getCode()),DictionaryDetail::getCode,dto.getCode())
                    .and(StrUtil.isNotEmpty(dto.getKeyword()), wrapper -> wrapper.like(DictionaryDetail::getName, dto.getKeyword()).or().like(DictionaryDetail::getCode, dto.getKeyword()))
                    .eq(ObjectUtil.isNotEmpty(dto.getItemId()) && dto.getItemId() != 0,DictionaryDetail::getItemId,dto.getItemId())
                    .select(DictionaryDetail.class, x -> VoToColumnUtil.fieldsToColumns(DictionaryDetailPageVo.class).contains(x.getProperty()))
                    .orderByAsc(DictionaryDetail::getSortCode);

        IPage<DictionaryDetail> page = dictionarydetailService.page(ConventPage.getPage(dto), queryWrapper);
        PageOutput<DictionaryDetailPageVo> pageOutput = ConventPage.getPageOutput(page, DictionaryDetailPageVo.class);
        return R.ok(pageOutput);
    }

    @GetMapping("/info")
    @ApiOperation(value = "获取当前数据字典详情的详情")
    public R info(@RequestParam Long id){
        DictionaryDetail dictionaryDetail = dictionarydetailService.getById(id);
        if (dictionaryDetail == null) {
            R.error("找不到此字典详情！");
        }
        return R.ok(BeanUtil.toBean(dictionaryDetail, DictionaryDetailVo.class));
    }

    @PostMapping
    @ApiOperation(value = "新增数据字典详情")
    public R add(@Valid @RequestBody AddDictionaryDetailDto dto){

        long count = dictionarydetailService.count(Wrappers.<DictionaryDetail>query().lambda().eq(DictionaryDetail::getItemId, dto.getItemId())
                .and(wrapper -> wrapper.eq(DictionaryDetail::getName, dto.getName())
                        .or().eq(DictionaryDetail::getValue, dto.getValue())
                        .or().eq(DictionaryDetail::getCode, dto.getCode())));
        if(count > 0){
            return R.error("字典名称、编码或值已经存在！");
        }

        DictionaryDetail dictionaryDetail = BeanUtil.toBean(dto, DictionaryDetail.class);

        boolean isSuccess = dictionarydetailService.save(dictionaryDetail);
        if (isSuccess) dictionarydetailService.loadCaches();
        return R.ok(isSuccess);
    }

    @PutMapping
    @ApiOperation(value = "修改数据字典详情")
    public R update(@Valid @RequestBody UpdateDictionaryDetailDto dto){
        long count = dictionarydetailService.count(Wrappers.<DictionaryDetail>query().lambda()
                .eq(DictionaryDetail::getItemId, dto.getItemId())
                .ne(DictionaryDetail::getId,dto.getId())
                .and(wrapper -> wrapper.eq(DictionaryDetail::getName, dto.getName())
                        .or().eq(DictionaryDetail::getValue, dto.getValue())
                        .or().eq(DictionaryDetail::getCode, dto.getCode())));
        if(count > 0){
            return R.error("字典名称、编码或值已经存在！");
        }
        DictionaryDetail dictionaryItem = BeanUtil.toBean(dto, DictionaryDetail.class);

        boolean isSuccess = dictionarydetailService.updateById(dictionaryItem);
        if (isSuccess) dictionarydetailService.loadCaches();
        return R.ok(isSuccess);
    }

    @DeleteMapping
    @ApiOperation(value = "删除数据字典详情")
    public R delete(@RequestBody List<Long> ids){
        return R.ok(dictionarydetailService.removeBatchByIds(ids));
    }
}
